import tkinter as tk
import tkinter.ttk as ttk
from tkinter.scrolledtext import ScrolledText
from mergeExcel import find_excel_by_dir, mergeExcel, find_excel_by_dir_re
from tkinter.messagebox import showinfo, showerror
import os
import json
import time
import pythoncom
# 弹出窗口
"""
    2020-4-20 加入config.json 保存
"""


class PopWin():
    def __init__(self, root, settings, name="PopWin", destDir="."):
        self.root = root
        self.tl = tk.Toplevel(root)
        self.tl.title(" %s [%s]" % (name, destDir))
        self.destDir = destDir
        self.settings = settings

        self.srctxt = ScrolledText(self.tl,
                width=60, height=15, bg="black", fg="white") #undo??
        # set tag in text. so can change the font and color
        self.srctxt.tag_config("warn", foreground="yellow", font="heiti 10 bold")
        self.srctxt.pack()

        self.bar = ttk.Progressbar(self.tl, length=200)
        self.bar.pack(pady=10)
        self.bar.pack()
        self.tl.resizable(False,False) #阻止用户调整窗口大小
        self.json_str = ""
        self.config_fname = "config.json"


    def run(self):
        pythoncom.CoInitialize()
        if self.settings["recrusive"] == False:
            filelist = find_excel_by_dir(self.destDir)
        else:
            filelist = find_excel_by_dir_re(self.destDir)
            
        self.filelist = filelist
        self.bar["value"] = 0
        self.bar["maximum"] = len(filelist)
        sheets = None #

        files = len(filelist)
        if self.settings["copy_by_sht"] == True:
            sheets = self.set_sheet_copy_setings()
            if sheets == None: # 按sheet copy 失败了
                self.tl.destroy()
                return

        self.srctxt_prt("找到 %d 个 表格文件\n" % files)
        if files > 0 :
            self.tl.protocol("WM_DELETE_WINDOW", self.donothing) #正式合并前禁止关窗口

            res = mergeExcel(self.filelist,self.destDir, 
                self.callback, self.settings["headers"],
                sheets, self.settings["use_fname"]) # if sheets==None 一般情况 合并方式具体实现 在mergeExcel模块
            print(".....mergeExcel return......")
            if res[0] == True: #sucess
                self.srctxt_warn( "合并成功！！\n 文件保存在[%s]" % res[1])
            else:
                self.srctxt_warn( "合并失败!!\n MSG: %s" % res[1])

            self.tl.protocol("WM_DELETE_WINDOW", self.tl.destroy) #恢复关闭功能
        else:
            showinfo("Tint", "目录[%s] 中未发现表格文件。请重新选择或退出" % self.destDir)
            self.tl.destroy()

    def srctxt_prt(self, s):
        """
            在 srolltext 中 输出反馈信息
        """
        self.srctxt.insert(tk.END, s)
        self.srctxt.see(tk.END)

    def srctxt_warn(self, s):
        self.srctxt.insert(tk.END, s, "warn") # insert with tag
        self.srctxt.see(tk.END)

    
    def callback(self, fname, err=None):
        """ 
            回调 -> 使用在 真正做事的函数中
        """

        if err == None and fname != None:
            prt_fname = os.path.relpath(fname,self.destDir)
            self.srctxt_prt("采集>> %s\n" % prt_fname)
            self.bar["value"] += 1
            self.tl.update()
            if self.bar["value"] >= self.bar["maximum"]:
                self.srctxt_warn("采集完毕，保存中...请稍等")
        elif err != None:
            self.srctxt_warn(err["msg"])
        else:
            pass

    def set_json_str(self):
        """
            设置 json string
        """
        json_str = self.tmp_txt.get("1.0", tk.END)
        self.json_str = json_str.replace("\n","")
        self.wait = False
    
    def set_sheet_copy_setings(self):
        """
            强出录入 seting string 的窗口
        """
        #生成sheets ->{"shtname": row_head, ....}
        sheets_settings = None
        try:
            self.tmp_tl = tk.Toplevel(self.tl)
            self.tmp_txt = ScrolledText(self.tmp_tl, width=40, height=10)
            self.tmp_txt.pack(pady=10)
            txt = self.read_config()
            if txt == "": 
                txt = self.settings["json_tp"]
            self.tmp_txt.insert(tk.END, txt)
            tk.Button(self.tmp_tl, text="确定", 
                    command=self.set_json_str).pack()
            self.wait = True
            self.cancel = False
            self.tmp_tl.protocol("WM_DELETE_WINDOW", self.cancel_set)
            while self.wait:
                time.sleep(1)
            if self.cancel == False:
                sheets_settings = json.loads(self.json_str)
                self.save_config(self.json_str)
        except Exception as e:
            print("[Err] >> load json string failed " + str(e))
            sheets_settings = None
            showerror("Error", "设置sheet 失败, 数据格式不对！！")
            self.tl.destroy()
        finally:
            self.tmp_tl.destroy()
            return sheets_settings


    def donothing(self):
        ''' do nothing.'''
        pass

    def cancel_set(self):
        """
            set sheet config 时 取消
        """
        self.cancel = True
        self.wait = False

    def read_config(self):
        """
        """
        ret = ""
        try:
            with open(self.config_fname, "r") as fr:
                ret = fr.read()
        except Exception as e:
            print("[popWIn Err] >>> config file error:\n %s" + str(e))
            ret =  ""
        finally:
            return ret

    def save_config(self, data):
        """
            save config file
        """
        with open(self.config_fname, "w") as fw:
            fw.write(data)



